
#include "Debug.h"

namespace p2 {

char const* Debug::s_logFile = "p2.log";
char const* Debug::s_assertFormat = "assertion '%s' failed in file '%s', line %d";
Timer Debug::s_logTimer(true);

void Debug::assertLog(char const* file, int32 line, char const* cond)
{
	char txt[MAX_MESSAGE_BYTES];
	size_t const maxPrefixChars = MAX_MESSAGE_BYTES - 1;
	_snprintf(txt, maxPrefixChars, s_assertFormat, cond, file, line);
    throw ExitException(txt);
}

void Debug::log(char const* file, int32 line, char const* msg)
{
    char txt[MAX_MESSAGE_BYTES];
    size_t const maxPrefixChars = MAX_MESSAGE_BYTES - 1;
    _snprintf(txt, maxPrefixChars, "%lf: %s: %d: %s", s_logTimer.getElapsedTimeInSec(), file, line, msg);

    FILE* logFile = fopen(s_logFile, "at");
    if (logFile) {
        fputs(txt, logFile);
        fputc('\n', logFile);
    }
    fclose(logFile);
}

void Debug::logF(char const* file, int32 line, char const* fmt, ...)
{
	char txt[MAX_MESSAGE_BYTES];
	size_t const maxPrefixChars = MAX_MESSAGE_BYTES - 1;
	_snprintf(txt, maxPrefixChars, "%lf: %s: %d: ", s_logTimer.getElapsedTimeInSec(), file, line);

	va_list arg;
	va_start(arg, fmt);
	size_t len = strlen(txt);
	_vsnprintf(txt + len, maxPrefixChars - len, fmt, arg);
	va_end(arg);

	FILE* logFile = fopen(s_logFile, "at");
	if (logFile) {
		fputs(txt, logFile);
        fputc('\n', logFile);
	}
	fclose(logFile);
}

}
